package com.luke.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.WatchedEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.List;

/**
 * @Descrtption CuratorCreate
 * @Author luke
 * @Date 2020/5/22
 **/
public class CuratorWatcherTest {

    private String IP = "192.168.0.17:2181";

    private CuratorFramework client;

    @Before
    public void before(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
        client = CuratorFrameworkFactory.builder()
                .connectString(IP)//地址端口
                .sessionTimeoutMs(5000)//会话超时
                .retryPolicy(retryPolicy)//重连机制
                .namespace("create")//命名空间
                .build();
        client.start();
    }

    @After
    public void after(){
        client.close();
    }

    @Test
    public void watcher1() throws Exception{
        //监听子节点数据变化情况（增加、删除）
        List<String> resultList = client.getChildren().usingWatcher(new CuratorWatcher() {
            public void process(WatchedEvent watchedEvent) throws Exception {
                String path = watchedEvent.getPath();//父节点
                client.getChildren().usingWatcher(this).forPath(path);//再次注册监听器
            }
        }).forPath("/node2");
        System.out.println("resultList:"+resultList);//返回监听节点下的所有子节点
        System.in.read();
    }

}
